﻿using CaseManagerLibrary.Log;
using PSDClientService;
using PSDClientService.SystemSettings;
using PSDLib;
using PSDLib.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSDClientListener
{
    public class ClientListener
    {
        public PSDClientState PSDClientState { get; set; }
        public ILog Logger { get; set; }
        public MessageManager MessageManager { get; set; }

        public CycleRestartPSDClientManager RestartPSDClientManager { get; set; }

        public KeepAliveManager KeepAliveManager { get; set; }

        private string LogType { get; set; } = "c";
        private bool RunAsService { get; set; }

        private string UUID = "";

        public ClientListener()
        {
            PSDClientState = new PSDClientState();
            RestartPSDClientManager = new CycleRestartPSDClientManager();
            MessageManager = new MessageManager(this);
            KeepAliveManager = new KeepAliveManager(this);
        }

        public void Init(string logtype, bool runAsService)
        {
            LogType = logtype;
            RunAsService = runAsService;
            UUID = DeviceUUID.GetUUID();

            switch (logtype)
            {
                case "text":
                    Logger = new TextLog(AppSettings.Setting.LogPath);
                    break;
                case "sql":
                    Logger = new SQLiteLog(AppSettings.Setting.LogPath, "PSDListener", UUID);
                    break;
                default:
                    Logger = new ConsoleLog();
                    break;
            }

            RestartPSDClientManager.Init();
            MessageManager.Init();
            KeepAliveManager.Init();
        }

        public void Start()
        {
            try
            {
                RestartPSDClientManager.Start();
                MessageManager.Start();
                KeepAliveManager.Start();
            }
            catch (Exception ex)
            {
            }
        }

        public void Stop()
        {
            try
            {
                KeepAliveManager.Stop();
                RestartPSDClientManager.Stop();
                MessageManager.Stop();
            }
            catch (Exception ex)
            {
            }
        }

        public void Dispose()
        { }

        public void KeepAlive(KeepAliveMessage msg)
        {
            KeepAliveManager.KeepAlive(msg.CheckTime);
        }
    }
}
